package com.yc.web.controller.common;

import com.yc.common.annotation.Log;
import com.yc.common.enums.OperationType;
import com.yc.common.core.domain.AjaxResult;
import com.yc.common.exceptions.captcha.CaptchaException;
import com.yc.common.exceptions.captcha.CaptchaExpireException;
import com.yc.system.service.CaptchaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@Api(tags = "验证码管理")
@RestController
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    /**
     * 获取验证码id （登录、注册）
     *
     * @return 验证码ID
     */
    @Log(module = "验证码管理", type = OperationType.QUERY, description = "获取验证码ID")
    @ApiOperation("获取验证码ID")
    @GetMapping("/getCaptchaId")
    public AjaxResult getCaptcha() {
        try {
            // 生成验证码并获取验证码ID
            String captchaId = captchaService.createCaptcha();

            // 返回验证码ID
            AjaxResult ajax = AjaxResult.success();
            ajax.put("captchaId", captchaId);

            return ajax;
        } catch (Exception e) {
            throw new CaptchaException("生成验证码失败，请重试");
        }
    }

    /**
     * 获取验证码图片 （登录、注册）
     *
     * @param captchaId 验证码ID
     * @param response  HTTP响应
     */
    @Log(module = "验证码管理", type = OperationType.OTHER, description = "获取验证码信息")
    @ApiOperation("获取验证码图片")
    @GetMapping(value = "/getCaptchaImage/{captchaId}", produces = MediaType.IMAGE_JPEG_VALUE)
    public void getCaptchaImage(@PathVariable("captchaId") String captchaId,
                                HttpServletResponse response) throws IOException {
        try {
            // 获取验证码图片
            BufferedImage image = captchaService.getCaptchaImage(captchaId);

            if (image == null) {
                throw new CaptchaExpireException("验证码不存在或已过期");
            }

            // 设置响应头
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);

            // 输出图片
            try (OutputStream outputStream = response.getOutputStream()) {
                ImageIO.write(image, "JPEG", outputStream);
                outputStream.flush();
            }
        } catch (CaptchaExpireException e) {
            // 对于验证码不存在的情况，返回特定的错误图片或状态码
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("Captcha not found or expired");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error generating captcha image");
        }
    }

    /**
     * 获取验证码图片 （忘记密码）
     *
     * @param email 邮箱
     */
    @Log(module = "验证码管理", type = OperationType.OTHER, description = "发送验证码到邮箱")
    @ApiOperation("发送验证码至邮箱")
    @GetMapping("/sendCaptchaToEmail/{email}")
    public AjaxResult sendCaptchaToEmail(@PathVariable String email) {
        try {
            // 验证邮箱格式
            if (email == null || email.isEmpty() || !email.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
                return AjaxResult.error("邮箱格式不正确");
            }

            // 生成验证码并发送到邮箱
            String captchaId = captchaService.createAndSendEmailCaptcha(email);

            // 返回验证码ID
            AjaxResult ajax = AjaxResult.success("验证码已发送到邮箱");
            ajax.put("captchaId", captchaId);

            return ajax;
        } catch (Exception e) {
            return AjaxResult.error("发送验证码失败，请重试");
        }
    }
}